var SceneEditor=function(options){
	this.ctx=options.ctx;
	this.sceneId=options.sceneId;
	this.x=options.x;
	this.y=options.y;
	this.z=options.z;
	this.heading=options.heading;
	this.pitch=options.pitch;
	this.roll=options.roll;
	this.sceneId=options.sceneId;
	this.container=options.container;
	this.viewer;
	this.init();
	return this;
}

SceneEditor.prototype.init = function (){
	var _this=this;
	layer.load(2);
    _this.ajaxFunc(_this.ctx+"/scene/getById",{
		sceneId:_this.sceneId,
		hasMap:'1',
		hasModel:'1',
	}, "json",function(res){
		layer.closeAll('loading');
	    if (undefined!=res && 200==res.code) {
	    	var data=res.data
	    	data.url=_this.ctx;
	    	_this.x=data.x;
	    	_this.y=data.y;
	    	_this.z=data.z;
	    	_this.heading=data.heading;
	    	_this.pitch=data.pitch;
	    	_this.roll=data.roll;
	    	data.geocoder=true;
	       _this.globe= new VFG.Viewer(_this.container,data);
	       _this.viewer=_this.globe.viewer;
	    } else {
	        layer.msg(res.message, {icon: 2});
	        _this.globe= new VFG.Viewer(_this.container,{geocoder:true});
	        _this.viewer=_this.globe.viewer;
	    }
	    _this.initLayerTree();
	    _this.initClick();
	    _this.initMenuTree();
	});
}



SceneEditor.prototype.initClick = function (){
	var _this=this;
    $('#sceneClassify').click(function () {
    	_this.editLayer();
    })
    $('#sceneSetting').click(function () {
    	_this.editScene();
    })
    
    $('#sceneLocation').click(function () {
    	_this.flyToLocation();
    })  
    $('#sceneRefresh').click(function () {
    	var treeObj =  $.fn.zTree.getZTreeObj("sceneLayer-"+_this.sceneId);
    	if(treeObj){
    		treeObj.reAsyncChildNodes(null, "refresh");
    	}
    }) 
    
    _this.globe.LEFT_CLICK_PRIMITIVE(function(e){
    	if(!_this.isDrag && !_this.isDraw){
    		if("Point"==e.type){
    			_this.operationPoint(e.position,e.id,e.type);
    		}
    		else if("Polyline"==e.type){
    			_this.operationPolyline(e.position,e.id,e.type);
    		}
    		else if("Polygon"==e.type){
    			_this.operationPolygon(e.position,e.id,e.type);
    		}
    		else if("VideoPlane"==e.type){
    			_this.operationVideoPlane(e.position,e.id,e.type);
    		}
    	}
    });
    _this.globe.CAMERA_MOVE_END(function(e){
    });
    _this.globe.LEFT_DOUBLE_CLICK_PRIMITIVE(function(e){
    	console.log(e)
    });
    
    
    
}

SceneEditor.prototype.flyToLocation = function (){
	var _this=this;
	_this.globe.flyTo({
		position:{
			x:_this.x,
			y:_this.y,
			z:_this.z,
		},
		orientation:{
			heading:_this.heading,
			pitch:_this.pitch,
			roll:_this.roll,
		}
	});
}

SceneEditor.prototype.editScene = function() {
	var _this=this;
	 layer.load(2);
	 _this._Ajax('get',_this.ctx+"/scene/setting",{sceneId:_this.sceneId},'html',function(e){
		layer.closeAll();
		layer.open({
		   id:'editScene',
           type: 1,
           anim:5,
           title:'场景配置',
           area: '300px',
           content:e,
           shade:0,
           offset: ['0px', '224px'],	
           fixed:true,
           move:false,
		    skin:'layui-layer  layui-layer-adminRight layui-layer-city',
           success: function (layero, dIndex) {
              $(layero).children('.layui-layer-content').css('overflow', 'hidden');
              
              form.render();
              form.on('submit(submitBaseBizSceneForm)', function (data) {
	        	    layer.load(2);
	                var formData={}; 
	                for(var key in data.field){
	                	formData['bizScene.'+key]=data.field[key];
	                }
	                _this.ajaxFunc(_this.ctx+"/scene/save",formData, "json", function(res){
		                layer.closeAll('loading');
		                if (200==res.code) {
		                    layer.msg(res.message, {icon: 1});
		                    $("#sceneBuiderNameTd").html(res.data.title);
		                } else {
		                    layer.msg(res.message, {icon: 2});
		                }
	                });
	        	    return false;
	        	});
              
              	form.on('submit(submitVisualAngleSceneForm)', function (data) {
	               	 var visualAngle= _this.globe.getVisualAngle();
	            	 if(visualAngle){
	            		 $("#sceneX").val(visualAngle.position.x);
	            		 $("#sceneY").val(visualAngle.position.y);
	            		 $("#sceneZ").val(visualAngle.position.z);
	            		 $("#sceneHeading").val(visualAngle.heading);
	            		 $("#scenePitch").val(visualAngle.pitch);
	            		 $("#sceneRoll").val(0);
	 	        	    layer.load(2);
		                var formData={}; 
		                formData['bizScene.id']=_this.sceneId;
		                formData['bizScene.x']=visualAngle.position.x;
		                formData['bizScene.y']=visualAngle.position.y;
		                formData['bizScene.z']=visualAngle.position.z;
		                formData['bizScene.heading']=visualAngle.heading;
		                formData['bizScene.pitch']=visualAngle.pitch;
		                formData['bizScene.roll']=0;
		                _this.ajaxFunc(_this.ctx+"/scene/save",formData, "json", function(res){
			                layer.closeAll('loading');
			                if (200==res.code) {
			                    layer.msg(res.message, {icon: 1});
			                    _this.x=res.data.x*1;
			                    _this.y=res.data.y*1;
			                    _this.z=res.data.z*1;
			                    _this.heading=res.data.heading*1;
			                    _this.pitch=res.data.pitch*1;
			                    _this.roll=res.data.roll*1;
			                } else {
			                    layer.msg(res.message, {icon: 2});
			                }
		                });
		                return false;
	            	 }else{
	            		 layer.msg("拾取视角失败!", {icon: 2});
	            		 return false; 
	            	 }
	        	});              
			},
			end:function(){
			}
		});	
	});
}

SceneEditor.prototype._Ajax = function(reqType, url, data, dataType, callback) {
	$.ajax({
		type: reqType,
		url: encodeURI(encodeURI(url)),
		data: data,
		dataType: dataType ? dataType : 'html',
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		async: true,
		cache: false,
		success: function(response) {
			if (callback != null) {
				callback(response);
			}
		}
	});
}

SceneEditor.prototype.ajaxFunc = function(url, data, dataType, callback){
	if(dataType == undefined || dataType == null){
		dataType = "html";
	}
	var result;
	$.ajax({
		type : "post",
		url : encodeURI(encodeURI(url)),
		data : data,
		dataType : dataType,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		async: true,
		cache: false,
		success:function(response){
			result = response;
			//扩展回调函数
			if( callback != null ){
				callback(result);
			}
		}
	});
	return result;
};

SceneEditor.prototype.getVisualHeight = function(){
 	 var visualAngle= this.globe.getVisualAngle();
	 if(visualAngle){
		 return visualAngle.position.z;
	 }else{
		 return 0;
	 }
};

SceneEditor.prototype.selectIcon=function(type,callback){
	var _this=this;
    layer.open({
        type: 1,
        title:'图标库',
        area:'250px',
        resize :false,
        shade:0,
        offset: ['0px', '576px'],	
        fixed:true,
        move:false,
		skin:'layui-layer  layui-layer-adminRight layui-layer-city',
        content: $('#modelIconForBizStylePoint').html(),
        success: function (layero, dIndex) {
            $(layero).children('.layui-layer-content').css('overflow', 'visible');
            var insTbIconForBizStylePoint = table.render({
                elem: '#tableIconForBizStylePoint',
                url: _this.ctx+'/biz/icon/listData',
                page: true,
                toolbar: false,
                skin:'nob',// 无边框风格
                page: {
                    layout: ['prev', 'page', 'next','count'] //自定义分页布局
                    //,curr: 5 //设定初始在第 5 页
                    ,groups:5 //只显示 1 个连续页码
                    ,first: false //不显示首页
                    ,last: false //不显示尾页
                },   
                where:{
                	type:type
                },
                cols: [[
                    {
                        align: 'center', templet: function (d) {
                        	if(d.url)
                            	return '<img src="'+_this.ctx+'/'+d.url+'" />';
                            else
                            	return '';
                        }, title: '图标',
                    },
                    {field: 'name', sort: false, title: '名称'}
                ]],
                done:function () {
            	    $(".layui-table-box").css("border-width","0px");
            	    $(".layui-table-header tr").css("height","30px");
            	    $(".layui-table-header tr").css("background-color","#444");
            	    $(".layui-table-header tr span").css("color","hsla(0, 0%, 100%, .8)");
            	    $(".layui-table-body tr").css("height","30px");
            	}                
            });
            
            upload.render({
                elem: '#uploadIconBtn'
                ,url: _this.ctx+'/biz/icon/upload?type='+type
                ,accept: 'images'
             	,before: function(obj){ 
          	    layer.load(); 
          	  }
          	  ,done: function(res, index, upload){
          		layer.closeAll('loading'); //关闭loading
                  if (200==res.code) {
                      layer.msg(res.message, {icon: 1});
                      insTbIconForBizStylePoint.reload();
                  } else {
                      layer.msg(res.message, {icon: 2});
                  }
          	  }
          	  ,error: function(index, upload){
          	    layer.closeAll('loading');
          	    layer.msg("上传失败！", {icon: 2});
          	  }       
              });
            
            table.on('row(tableIconForBizStylePoint)', function(obj){
            	var data = obj.data;
              	obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
              	if(callback){
              		callback(data)
              	}
            });
            form.on('submit(formSubSearchIconForBizStylePoint)', function (data) {
            	insTbIconForBizStylePoint.reload({where: data.field}, 'data');
            });
        },
        end:function(){
        }
    });
}

SceneEditor.prototype.selectVideo = function (treeNode,callback) {
	var _this=this;
	layer.load(2);
	_this._Ajax('get',_this.ctx+"/biz/video/selectList",{sceneId:_this.sceneId,targetId:treeNode.id},'html',function(e){
		layer.closeAll('loading');   
		var layerIndex= layer.open({
		    	id:'selectVideo',
		        title: '编辑【'+treeNode.name+'】视频资源',
		        type: 1,
		        area:'250px',
		        shade:0,
		        offset: ['0px', '576px'],
		        fixed:true,
		        move:false,
		        skin:'layui-layer  layui-layer-adminRight layui-layer-city',
			    content: e,
			    success: function (layero, dIndex) {
		            $(layero).children('.layui-layer-content').css('overflow', 'hidden');
		            var insTb = table.render({
		                elem: '#tableSelectBizVideo',
		                url: _this.ctx+'/biz/video/listData', 
		                page: true,
		                toolbar: false,
		                skin:'nob',// 无边框风格
		                page: {
		                    layout: ['prev', 'page', 'next','count'] //自定义分页布局
		                    //,curr: 5 //设定初始在第 5 页
		                    ,groups:5 //只显示 1 个连续页码
		                    ,first: false //不显示首页
		                    ,last: false //不显示尾页
		                }, 
		                where:{
		                	sceneId:_this.sceneId	
		                },
		                cols: [[
		                    {field: 'name', sort: false, title: '名称'},
		                ]],
		            });
		            
		            // 搜索
		            form.on('submit(formSubSearchSelectBizModel)', function (data) {
		                insTb.reload({where: data.field}, 'data');
		            });
		            
		            //监听行单击事件（双击事件为：rowDouble）
		            table.on('row(tableSelectBizVideo)', function(obj){
		            	var data = obj.data;
		              	obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		              	if(callback){
		            	  callback(data);
		              	}
		            });
				},
				end:function(){
				}
	    	});  
	});
};

SceneEditor.prototype.selectModel = function (treeNode,type,callback) {
	var _this=this;
	layer.load(2);
	_this._Ajax('get',_this.ctx+"/biz/model/selectList",{sceneId:_this.sceneId,targetId:treeNode.id},'html',function(e){
		layer.closeAll('loading');   
		var layerIndex= layer.open({
		    	id:'selectModel',
		        title: '编辑【'+treeNode.name+'】模型资源',
		        type: 1,
		        area:'250px',
		        shade:0,
		        offset: ['0px', '576px'],
		        fixed:true,
		        move:false,
		        skin:'layui-layer  layui-layer-adminRight layui-layer-city',
			    content: e,
			    success: function (layero, dIndex) {
		            $(layero).children('.layui-layer-content').css('overflow', 'hidden');
		            var insTb = table.render({
		                elem: '#tableSelectBizModel',
		                url: _this.ctx+'/biz/model/listData', 
		                page: true,
		                toolbar: false,
		                skin:'nob',// 无边框风格
		                page: {
		                    layout: ['prev', 'page', 'next','count'] //自定义分页布局
		                    //,curr: 5 //设定初始在第 5 页
		                    ,groups:5 //只显示 1 个连续页码
		                    ,first: false //不显示首页
		                    ,last: false //不显示尾页
		                }, 
		                where:{
		                	type:'OBJ'
		                },
		                cols: [[
		                    {field: 'name', sort: false, title: '名称'},
		                ]],
		            });
		            //监听行单击事件（双击事件为：rowDouble）
		            table.on('row(tableSelectBizModel)', function(obj){
		            	var data = obj.data;
		              	obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		              	if(callback){
		            	  callback(data);
		              	}
		            });
				},
				end:function(){
				}
	    	});  
	});
};

